﻿using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace uTILLIty.Outlook.FlexFileAddIn
{
	public class WindowsHelper
	{
		//http://msdn.microsoft.com/en-us/library/windows/desktop/ms646309%28v=vs.85%29.aspx
		//http://social.msdn.microsoft.com/Forums/en-US/vbgeneral/thread/95fa600a-8877-4376-9383-48ff14cb4909
		//http://www.pinvoke.net/default.aspx/user32/registerhotkey.html

		/// <summary> The RegisterHotKey function defines a system-wide hot key </summary>
		/// <param name="hWnd">Handle to the window that will receive WM_HOTKEY messages  generated by the hot key.</param>
		/// <param name="id">Specifies the identifier of the hot key.</param>
		/// <param name="fsModifiers">Specifies keys that must be pressed in combination with the key  specified by the 'vk' parameter in order to generate the WM_HOTKEY message.</param>
		/// <param name="vk">Specifies the virtual-key code of the hot key</param>
		/// <returns><c>true</c> if the function succeeds, otherwise <c>false</c></returns>
		/// <seealso cref="http://msdn.microsoft.com/en-us/library/ms646309(VS.85).aspx"/>
		[DllImport("user32.dll", SetLastError = true)]
		[return: MarshalAs(UnmanagedType.Bool)]
		static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk);

		[DllImport("user32.dll")]
		private static extern bool UnregisterHotKey(IntPtr hWnd, int id);

		#region fields
		public static int ModAlt = 0x1;
		public static int ModControl = 0x2;
		public static int ModShift = 0x4;
		public static int ModWin = 0x8;
		public static int WmHotkey = 0x312;
		#endregion

		public static void RegisterHotKey(IntPtr hWnd, Keys key, int guid)
		{
			int modifiers = 0;

			if ((key & Keys.Alt) == Keys.Alt)
				modifiers = modifiers | ModAlt;

			if ((key & Keys.Control) == Keys.Control)
				modifiers = modifiers | ModControl;

			if ((key & Keys.Shift) == Keys.Shift)
				modifiers = modifiers | ModShift;

			Keys k = key & ~Keys.Control & ~Keys.Shift & ~Keys.Alt;
			RegisterHotKey(hWnd, guid, (uint)modifiers, (uint)k);
		}

		public static void UnRegisterHotKey(IntPtr hWnd, int guid)
		{
			try
			{
				UnregisterHotKey(hWnd, guid);
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.ToString());
			}
		}
	}
}